/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.editor.model;

/**
 *
 * @author Walter Lütgenau
 */
public class XmlUtils {
    /**
     * Convert the attribute value to an XML value, i.e. escape
     * the vulnerable parts.
     * 
     * @param input
     * @return
     */
    public static String attributeValueToXML(String input) {
        int length = input.length();
        char[] chars = input.toCharArray();
        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < length; i++) {
            // This will change, we need better support character level
            // entities.
            switch (input.charAt(i)) {
                // Character level entities.
                case '<':
                    buf.append("&lt;");
                    break;

                case '>':
                    buf.append("&gt;");
                    break;

                case '&':
                    buf.append("&amp;");
                    break;

                case '"':
                    buf.append("&quot;");
                    break;

                // Special characters
                case '\n':
                case '\t':
                case '\r':
                    break;

                default:
                    if (input.charAt(i) < ' ' || input.charAt(i) > 127) {
                        // If the character is outside of ascii, write the
                        // numeric value.
                        buf.append("&#");
                        buf.append(String.valueOf((int) input.charAt(i)));
                        buf.append(";");
                    } else
                        buf.append(input.charAt(i));
                    break;
            }
        }

        return buf.toString();
    }
}
